package com.briup.srms.base.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @program: sms
 * @description: RedisUtil
 * @author: charles
 * @create: 2021-09-14 19:27
 **/

@Component
public class RedisUtil {
    private static final Long SUCCESS = 1L;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    // =============================common============================



    /**
     * 获取锁
     * @param lockKey
     * @param value
     * @param expireTime：单位-秒
     * @return
     */
    public boolean getLock(String lockKey, Object value, int expireTime) {
        try {
            String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
            RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
            Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
            if (SUCCESS.equals(result)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 释放锁
     * @param lockKey
     * @param value
     * @return
     */
    public boolean releaseLock(String lockKey, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
        Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
        if (SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }


    // Redis缓存权限树固定key前缀
    private final static String PRIVILEGE_TREE_PREFIX = "privilege-";

    /**
     * 向Redis中缓存用户权限树
     * @param userId 用户ID
     * @param tree 权限树对象
     * @author: YuYan
     */
    public void cachePrivilegeTree(long userId, List tree) {
        redisTemplate.opsForValue().set(new StringBuffer().append(PRIVILEGE_TREE_PREFIX).append(userId).toString(), tree);
    }

    /**
     * 从Redis中取出缓存的权限树
     * @param userId 用户ID
     * @return 取出的权限树对象
     */
    public Object getPrivilegeTree(long userId) {
        return redisTemplate.opsForValue().get(new StringBuffer().append(PRIVILEGE_TREE_PREFIX).append(userId).toString());
    }


}
